//
//  ViewController.m
//  dispatch_source
//
//  Created by 青梅睿创公司 on 2018/2/26.
//  Copyright © 2018年 青梅睿创公司. All rights reserved.
//

#import "ViewController.h"
#import "NextViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NextViewController * nextVC = [[NextViewController alloc] init];
    
    [self presentViewController:nextVC animated:YES completion:nil];
}

- (void)go{
    __block NSInteger time = 0;
    
    // 倒计时时间
//    __block NSInteger timeOut = 6;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 每秒执行一次
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        if (time < 0) {
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"计时结束..");
                
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"---%lu", time);
            });
            
            time ++;
        }
        
        
        // 倒计时结束，关闭
        //        if (timeOut > 10) {
        //            dispatch_source_cancel(_timer);
        //
        //            dispatch_async(dispatch_get_main_queue(), ^{
        //                NSLog(@"计时结束..");
        //
        //            });
        //
        //        }else{
        //
        //            int seconds = timeOut % 60;
        //            NSString * timeStr = [NSString stringWithFormat:@"%d",seconds];
        //
        //            dispatch_async(dispatch_get_main_queue(), ^{
        //                NSLog(@"timeStr:%@", timeStr);
        //            });
        //
        //            timeOut--;
        //        }
        
        
        
    });
    
    dispatch_resume(_timer);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
